package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {


    @Autowired
    private TravelRepository travelRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    @Override
    public void insert(Travel travel) {
        travelRepository.insert(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public Travel get(String id) {
        //orElse方法从optional中取值，如果取不到返回null
        Travel travel = travelRepository.findById(id).orElse(null);
        UserInfo userInfo = userInfoService.get(travel.getUserId());
        travel.setAuthor(userInfo);
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDest(destination);
        return travel;
    }

    @Override
    public List<Travel> list() {
        return travelRepository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

        if(StringUtils.hasLength(qo.getDestId())){
            Criteria c = Criteria.where("destId").is(qo.getDestId());
            query.addCriteria(c);
        }

        TravelCondition day = qo.getDay();
        if(day != null){
            Criteria c = Criteria.where("day").gte(day.getMin()).lte(day.getMax());
            query.addCriteria(c);
        }

        //添加人均消费查询条件
        TravelCondition perExpend = qo.getPerExpend();
        if(perExpend != null){
            Criteria c = Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax());
            query.addCriteria(c);
        }



        Page<Travel> page = DBHelper.query(mongoTemplate, Travel.class, qo, query);
        //查询作者头像信息
        for (Travel travel : page) {
            UserInfo userinfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userinfo);
        }
        return page;
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        System.out.println(travel.getId());
        //新增
        if(!StringUtils.hasLength(travel.getId())){
            //防止id为空串，直接写入到数据库，导致自动生成_id不成功
            travel.setId(null);

            //请求目的地信息
            Destination destination = destinationService.get(travel.getDestId());
            travel.setDestName(destination.getName());

            travel.setCreateTime(new Date());
            travel.setReleaseTime(null);
            travel.setLastUpdateTime(new Date());




            travelRepository.save(travel);
        }
        else{
            travelRepository.save(travel);
        }
    }

    @Override
    public void audit(String id, Integer state) {
        //查询游记
        Travel travel = get(id);
        if(travel == null || travel.getState() != Travel.STATE_WAITING){
            throw new LogicException("参数异常");
        }
        if(state == Travel.STATE_RELEASE){
            travel.setState(Travel.STATE_RELEASE);
            //将发布时间设置成当前时间
            travel.setReleaseTime(new Date());
            //设置最后更新时间
            travel.setLastUpdateTime(new Date());
            //其他审批系统（审核人信息，审核意见）
        }
        else{
            travel.setState(Travel.STATE_REJECT);
            //拒绝发布，设置发布时间为null
            travel.setReleaseTime(null);
            travel.setLastUpdateTime(new Date());
        }
        this.update(travel);

    }

    @Override
    public List<Travel> travelsviewnumTop3(String destId) {
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel>  list = travelRepository.findByDestId(destId, pageable);
        return list;
    }


}
